package wang.app.demo.jwt;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.JWTVerifier;

import java.util.Date;

/**
 * @Author dj.wang
 * @Date 2020/6/19 22:24
 * @Version V1.0
 */
public class JwtUtil
{

    public static final String AUTH_HEADER_KEY = "Authorization";

    public static final String TOKEN_PREFIX = "Bearer ";

    /**
     * 校验token是否正确
     *
     * @param token  密钥
     * @param secret 用户的密码
     * @return 是否正确
     */
    public static boolean verify(String token, String userId, String secret)
    {
        try
        {
            Algorithm algorithm = Algorithm.HMAC256(secret);
            JWTVerifier verifier = JWT.require(algorithm)
                    .withClaim("userId", userId)
                    .build();
            DecodedJWT jwt = verifier.verify(token);
            return true;
        }
        catch (Exception exception)
        {
            return false;
        }
    }

    /**
     * 获得token中的信息
     *
     * @return token中包含的用户名
     */
    public static String getUserId(String token)
    {
        try
        {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim("userId").asString();
        }
        catch (JWTDecodeException e)
        {
            return null;
        }
    }

    /**
     * 生成签名,5min后过期
     *
     * @param userId 用户ID
     * @param secret 用户的密码
     * @return 加密的token
     */
    public static String sign(String userId, String secret, long expire)
    {
        try
        {
            Date now = new Date();
            Date expTime = new Date(now.getTime() + expire);
            Algorithm algorithm = Algorithm.HMAC256(secret);

            // 附带username信息
            return JWT.create()
                    .withClaim("userId", userId)
                    .withNotBefore(now)
                    .withExpiresAt(expTime)
                    .sign(algorithm);
        }
        catch (Exception e)
        {
            return null;
        }
    }
}
